package com.atguigu.yygh.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.atguigu.yygh.common.handler.YyghException;
import com.atguigu.yygh.oss.service.FileService;
import com.atguigu.yygh.oss.utils.ConstantPropertiesUtil;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {
    //文件上传
    @Override
    public String upload(MultipartFile file) {
        //1.获取参数
        // Endpoint以杭州为例，其它Region请按实际情况填写。
        String endpoint = ConstantPropertiesUtil.END_POINT;//地域节点
        String accessKeyId = ConstantPropertiesUtil.ACCESS_KEY_ID;//AccessKey ID：LTAI5tP5R9Bu7p1TY1Cpwxba
        String accessKeySecret = ConstantPropertiesUtil.ACCESS_KEY_SECRET;//AccessKey Secret：HKbQFPYhbLOCIJPRh930TO0QUER29a
        String bucketName = ConstantPropertiesUtil.BUCKET_NAME;//阿里云OSS对象存储服务Bucket名字:guli-file220314litiian
        //2.创建客户端对象
        OSS ossClient = new OSSClientBuilder().build(endpoint,accessKeyId,accessKeySecret);
        try {
            //3.准备文件参数
            InputStream inputStream = file.getInputStream();
            String fileName = file.getOriginalFilename();
            //3.2文件名不重复UUID+fileName
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            fileName = uuid+fileName;
            //3.3根据日期创建路径2022/07/30/+fileName
            String path = new DateTime().toString("yyyy/MM/dd");
            fileName = path+"/"+fileName;
            //4.上传文件
            ossClient.putObject(bucketName,fileName,inputStream);
            //5.获取url
            String url = "http://"+bucketName+"."+endpoint+"/"+fileName;
            return url;
        } catch (Exception e) {
            e.printStackTrace();
            throw new YyghException(20001,"上传文件失败");
        } finally {
            //6.关闭客户端
            if (ossClient!=null){
                ossClient.shutdown();
            }
        }
    }
}
